package com.zkingsoft.wechat;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.json.GsonBuilderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.bean.BizMaterial;
import com.zkingsoft.bean.BizUser;
import com.zkingsoft.bean.BizUserMaterial;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.dao.BizMaterialDao;
import com.zkingsoft.dao.BizUserMaterialDao;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.service.BizUserMaterialService;
import com.zkingsoft.tools.ImageMerge;
import com.zkingsoft.tools.ImageUtil;
import com.zkingsoft.wechat.vo.ImageElementVo;

/**
 * @description 素材相关接口
 * @author 姜友瑶
 * @date 2018-05-23 00:08
 */
@Controller
@RequestMapping(value = "/wxapi/material")
public class WxMaterialAction extends BaseAction {

	@Autowired
	private BizUserMaterialService userMaterialService;

	@Autowired
	private BizMaterialDao materialDao;

	@Autowired
	private BizUserMaterialDao bizUserMaterialDao;

	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Value("${file_storage_path}")
	private String fileStoragePath;
	@Value("${static_resource_url}")
	private String nginxUrl;

	/**
	 * 查询素材
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月16日
	 * @param bizStaff
	 * @return
	 */
	@RequestMapping(value = "/findMaterial")
	public @ResponseBody AjaxResult findMaterial(@RequestBody BizMaterial bizMaterial) {
		bizMaterial.setUserId(redisUserLoginUtils.getLoginUser().getUserId());
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, materialDao.selectInPageFront(bizMaterial),
				materialDao.selectTotalRecord(bizMaterial));
	}

	/**
	 * 查询个人收藏的素材
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月21日
	 * @param bizUserMaterial
	 * @return
	 */
	@RequestMapping(value = "/findMyMaterial")
	public @ResponseBody AjaxResult findMyMaterial(@RequestBody BizUserMaterial bizUserMaterial) {
		bizUserMaterial.setUserId(redisUserLoginUtils.getLoginUser().getUserId());
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, bizUserMaterialDao.selectInPageFront(bizUserMaterial),
				bizUserMaterialDao.selectTotalRecord(bizUserMaterial));
	}

	/**
	 * 编辑预览
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月27日
	 * @param imageElementVo
	 * @return
	 */
	@RequestMapping(value = "/viewMaterial")
	public @ResponseBody AjaxResult viewMaterial(@RequestBody ImageElementVo imageElementVo) {

		BizMaterial bizMaterial = materialDao.selectById(imageElementVo.getId());
		LogUtil.debug("图片合成参数={}", bizMaterial.getElement());
		String fileType = bizMaterial.getImg().substring(bizMaterial.getImg().lastIndexOf(".") + 1);
		String newFileName = UUIDUtil.getRandomID() + "." + fileType;
		// 获取合成文件的保存地址
		// 图片保存目录路径
		String savePath = bizMaterial.getImg().substring(0, bizMaterial.getImg().lastIndexOf("."));
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			uploadDir.mkdir();
		}
		// 获取合成文件的访问地址
		savePath=savePath + "/" + newFileName;
		 
		String path =  savePath.replace(fileStoragePath,nginxUrl);

		imageMerge(imageElementVo, bizMaterial, savePath);

		return new AjaxResult(AjaxResult.STATUS_SUCCESS, path);
	}

	/**
	 * 素材编辑
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月22日
	 * @param bizUserMaterial
	 * @return
	 */
	@RequestMapping(value = "/editMaterial")
	public @ResponseBody AjaxResult editMaterial(@RequestBody ImageElementVo imageElementVo) {

		BizMaterial bizMaterial = materialDao.selectById(imageElementVo.getId());
		LogUtil.debug("图片合成参数={}", bizMaterial.getElement());
		String fileType = bizMaterial.getImg().substring(bizMaterial.getImg().lastIndexOf(".") + 1);
		String newFileName = UUIDUtil.getRandomID() + "." + fileType;
		// 获取合成文件的保存地址
		// 图片保存目录路径
		String savePath = bizMaterial.getImg().substring(0, bizMaterial.getImg().lastIndexOf("."));
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			uploadDir.mkdir();
		}
		// 获取合成文件的访问地址
		savePath=savePath + "/" + newFileName;
		 
		String path =  savePath.replace(fileStoragePath,nginxUrl);

		imageMerge(imageElementVo, bizMaterial, savePath);
		// 设置收藏
		String userId = redisUserLoginUtils.getLoginUser().getUserId();
		BizUserMaterial um = new BizUserMaterial();
		um.setUserId(userId);
		um.setMaterialId(bizMaterial.getId());
		if (CollectionUtils.isEmpty(userMaterialService.findByModel(um))) {
			um.setId(UUIDUtil.getRandomID());
			um.setCreateBy("system");
			um.setUpdateBy("system");
			um.setImg(bizMaterial.getImg());
			um.setPath(path);
			um.setElement(bizMaterial.getElement());
			um.setEditionImg(savePath);
			// 更新被收藏的次数
			bizMaterial.setCollectionTimes(bizMaterial.getCollectionTimes() + 1);
			materialDao.updateByModel(bizMaterial);
			int i = bizUserMaterialDao.insert(um);
			if (i > 0) {
				return new AjaxResult(AjaxResult.STATUS_SUCCESS, "编辑保存成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_FAIL, "编辑保存失败");
			}
		} else {
			um.setEditionImg(savePath);
			um.setPath(path);
			bizUserMaterialDao.updateByModel(um);
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, "编辑成功");
		}
	}

	/**
	 * 图片合成方法
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月27日
	 * @param imageElementVo
	 * @param bizMaterial
	 * @param savePath
	 */
	private void imageMerge(ImageElementVo imageElementVo, BizMaterial bizMaterial, String savePath) {
		GsonBuilder g = new GsonBuilder();
		List<ImageMerge> imageMergeList = g.create().fromJson(bizMaterial.getElement(),
				new TypeToken<List<ImageMerge>>() {
				}.getType());

		// 读取图片文件，得到BufferedImage对象
		BufferedImage bimg = null;
		try {
			bimg = ImageIO.read(new FileInputStream(bizMaterial.getImg()));
		} catch (IOException e) {
			e.printStackTrace();
			throw new GlobleException("素材编辑失败", e, "");
		}
		if (CollectionUtils.isNotEmpty(imageMergeList)) {
			try {
				int i = 0;
				for (ImageMerge imageMerge : imageMergeList) {
					if (ImageMerge.IMG == imageMerge.getType()) {
						// ImageUtil.overlapImage(imageMerge);
						// 目前只支持文字
					} else if (ImageMerge.STR == imageMerge.getType()) {
						imageMerge.setText(imageElementVo.getTextList().get(i));
						ImageUtil.drawString(bimg, imageMerge);
					} else {
						LogUtil.error("错误的合成参数,{}", imageMerge.getType());
					}
					i++;
				}

			} catch (IOException e) {
				e.printStackTrace();
				throw new GlobleException("素材编辑失败", e, "");
			}
		}
		// 保存新图片
		try {
			ImageIO.write(bimg, bizMaterial.getImg().substring(bizMaterial.getImg().lastIndexOf(".") + 1),
					new FileOutputStream(savePath));
		} catch (IOException e) {
			e.printStackTrace();
			throw new GlobleException("素材编辑失败", e, "");
		}
	}

	/**
	 * 收藏素材
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月22日
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/collectMaterial/{id}")
	public @ResponseBody AjaxResult collectMaterial(@PathVariable String id) {
		BizUser user = redisUserLoginUtils.getLoginUser();
		BizUserMaterial bizUserMaterial = new BizUserMaterial();
		bizUserMaterial.setMaterialId(id);
		bizUserMaterial.setUserId(user.getUserId());

		if (CollectionUtils.isEmpty(userMaterialService.findByModel(bizUserMaterial))) {

			int i = userMaterialService.collectMaterial(id, user.getUserId());

			if (i > 0) {
				return new AjaxResult(AjaxResult.STATUS_SUCCESS, "收藏成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_FAIL, "收藏失败");
			}
		} else {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "该素材已经收藏");
		}

	}

	/**
	 * 取消收藏素材
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年7月22日
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/cancelCollectMaterial/{id}")
	public @ResponseBody AjaxResult cancelCollectMaterial(@PathVariable String id) {
		BizUser user = redisUserLoginUtils.getLoginUser();
		BizUserMaterial bizUserMaterial = new BizUserMaterial();
		bizUserMaterial.setMaterialId(id);
		bizUserMaterial.setUserId(user.getUserId());
		int i = userMaterialService.removeByModel(bizUserMaterial);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, "取消成功");
		} else {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "取消失败");
		}

	}

}